# -*- coding: utf-8 -*-

"""
Module implementing MainWindow.
"""
import socket
from time import sleep

from PyQt5 import QtWidgets, QtGui
from PyQt5.QtCore import pyqtSlot, QTimer
from PyQt5.QtWidgets import QMainWindow

from Ui_UDP_to_TCP_mainwindow import Ui_MainWindow


class MainWindow(QMainWindow, Ui_MainWindow):
    """
    Class documentation goes here.
    """
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent widget
        @type QWidget
        """
        super(MainWindow, self).__init__(parent)

        self.setupUi(self)

        #禁止窗口最大化以及最小化，固定长度和宽度
        self.setFixedSize(self.width(), self.height())

        #开始连接数据
        self.send_num = 0
        self.receive_num = 0
        self.udp_socket = None

        #UDP socket


        #实例化定时器
        self.udp_timer = QTimer(self)

        #定时器读取UDP数据
        self.udp_timer.timeout.connect(self.recive_data)

        #status 显示收和发的字符数量
        self.status_set()

        #设置窗口图标.ico
        self.setWindowIcon(QtGui.QIcon('./girl.ico'))

        #刷新一下连接参数
        self.refresh()

    # 重载窗口关闭事件
    def closeEvent(self, e):
        # 关闭定时器，停止读取接收数据
        self.udp_timer.close()

        # 关闭串口
        if self.udp_socket != None:
            self.udp_socket.close()

    #接受UDP数据
    def recive_data(self):

        data = self.udp_socket.recv(1024)
        self.receive_num+=1024

        self.textBrowser_display.append(data.decode("utf-8"))

        self.status_set()


    #状态定义
    def status_set(self):
        status_str = '发送：' + '{0}'.format(self.send_num) + '  接收：' + '{0}'.format(self.receive_num)
        self.label_status.setText(status_str)

    #刷新连接参数
    def refresh(self):
        self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.udp_socket.bind(("",int(self.lineEdit_UDP_PORT.text())))

    
    @pyqtSlot()
    def on_pushButton_begin_clicked(self):
        """
        开始进行运行
        """

        #刷新连接参数
        self.refresh()

        #1、读取数据列

        self.pushButton_begin.setDisabled(True)
        self.udp_timer.start(2)
    
    @pyqtSlot()
    def on_pushButton_cancel_clicked(self):
        """
        Slot documentation goes here.
        """
        self.pushButton_begin.setDisabled(False)
        self.udp_socket.close()
        self.udp_timer.stop()
        self.receive_num = 0
        self.textBrowser_display.clear()
        self.status_set()



if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    ui = MainWindow()

    ui.show()
    sys.exit(app.exec_())